<?php
/*
Plugin Name: Shopping Cart
Plugin URI: http://wp-jacob.googlecode.com
Description: Implements a Google Checkout shopping cart
Version: 0.3-2
Author: Jacob Brunson
Author URI: http://jacobbrunson.com
*/

/*  Copyright 2008  Jacob Brunson  (email : wp-jacob.gpl.license@jacobbrunson.com )

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

define('SHOPCART_CART_URL', 'shopping-cart');

function parseInt($string) { 
    if(preg_match('/(\d+)/', $string, $array)) { 
        return $array[1]; 
    } else { 
        return 0; 
    } 
} 

$shopcart_subversion_revision = parseInt('$Rev: 196 $');


// This function tells WP to add a new "meta box"
function shopcart_add_box() 
{
    add_meta_box(
        'shopcartdiv', // id of the <div> we'll add
        'Shopping Cart Information', //title
        'shopcart_cartinfo_box', // callback function that will echo the box content
        'post' // where to add the box: on "post", "page", or "link" page
    );
}

function shopcart_add_post_javascript()
{
    $script_url = WP_PLUGIN_URL.'/'.dirname(plugin_basename(__FILE__)).'/post.js';
    wp_enqueue_script('shopcartpostscript', $script_url);
}

//////////////////////////////////////////////////////////////////////////////

function shopcart_add_options_javascript()
{
    $script_url = WP_PLUGIN_URL.'/'.dirname(plugin_basename(__FILE__)).'/options.js';
    wp_enqueue_script('shopcartoptionsscript', $script_url, array('prototype'));
}

function shopcart_load_options_page()
{
    include_once(WP_PLUGIN_DIR.'/'.dirname(plugin_basename(__FILE__)).'/options.php');
}

function shopcart_save_shipping_options()
{
    if (array_key_exists('shopcart_shipping_method', $_POST)) {
        switch (trim($_POST['shopcart_shipping_method'])) {
            case 'flat':
                $table = array_combine($_POST['shipping_flatrate_country'], $_POST['shipping_flatrate_rate']);
                if (get_option('shopcart_flatrate_table')) {
                    update_option('shopcart_flatrate_table', $table);
                } else {
                    add_option('shopcart_flatrate_table', $table);
                }
                break;

            default:
        }
    }
}

//////////////////////////////////////////////////////////////////////////////

$shopcart_item_meta_fields = array();

function shopcart_add_item_meta_field($title, $name, $type='input', $options=array())
{
    global $shopcart_item_meta_fields;
    $shopcart_item_meta_fields[] = array('title'=>$title, 'name'=>$name, 'type'=>$type, 'options'=>$options);
}

// This function echoes the content of our meta box, shown in the post editor
function shopcart_cartinfo_box() 
{
    global $shopcart_item_meta_fields;
    $conditions = array('new', 'used', 'refurbished');
    $edit_post = intval($_GET['post']);
    $price_meta = get_post_meta($edit_post, 'shopcart_price', true);
    $weight_meta = get_post_meta($edit_post, 'shopcart_weight', true);
    $upc = '';
    $image = '';
    $cond = 'new';
    $p = '';
    $w = '';
    $enabled = true && (get_post_meta($edit_post, 'shopcart_enabled', true) == 'true');
    $disabled = $enabled ? '' : 'disabled="disabled"';
    if ($edit_post > 0) {
        if (trim($price_meta) != '') {
            $p = number_format((float)$price_meta, 2);
        }
        if (trim($price_meta) != '') {
            $w = (float)$weight_meta;
        }
        $upc = get_post_meta($edit_post, 'shopcart_upc', true);
        $image = get_post_meta($edit_post, 'shopcart_image', true);
        $mpn = get_post_meta($edit_post, 'shopcart_mpn', true);
        $values = array();
        foreach ($shopcart_item_meta_fields as $field) {
            $values[$field['name']] = get_post_meta($edit_post, $field['name'], true);
        }
        $condition_meta = get_post_meta($edit_post, 'shopcart_condition', true);
        if (in_array($condition_meta, $conditions)) {
            $cond = $condition_meta;
        }
    }
    $out = 'Google Checkout: <select name="shopcart_enabled" onchange="enableCheckout(this.options.selectedIndex==0);">';
    if ($enabled) {
        $out .= '<option value="true" selected="selected">Enabled</option>
                <option value="false">Disabled</option>';
    } else {
        $out .= '<option value="true">Enabled</option>
                <option value="false" selected="selected">Disabled</option>';
    }
    $out .= "</select><br/>
    Price: <input name=\"shopcart_price\" value=\"$p\" $disabled /> ".get_option('shopcart_currency')."<br/>\n
          Weight: <input name=\"shopcart_weight\" value=\"$w\" $disabled /> ".get_option('shopcart_weight_units')."<br/>\n
          UPC Code: <input name=\"shopcart_upc\" value=\"$upc\" $disabled /><br/>\n
          Brand: <input name=\"shopcart_brand\" value=\"$brand\" $disabled /><br/>\n
          Manufacturer's Part Number: <input name=\"shopcart_mpn\" value=\"$mpn\" $disabled /><br/>\n
          Condition: <select name=\"shopcart_condition\" $disabled>\n";

    foreach ($conditions as $condition) {
        $out .= "<option value=\"$condition\" ";
        if ($condition == $cond) $out .= 'selected="selected" ';
        $out .= ">$condition</option>\n";
    }
    $out .= "</select><br/>";
    foreach ($shopcart_item_meta_fields as $field) {
        switch ($field['type']) {
            case 'select':
                $out .= "<select name=\"{$field['name']}\" $disabled>\n";
                foreach ($field['options'] as $key=>$opt) {
                    $selected = 'selected="selected" ' ? '' : $opt == $values[$field['name']];
                    $out .= "<option value=\"$opt\" $selected>$key</option>\n";
                }
                $out .= "</select></br>";
                break;

            case 'input':
            default:
                $out .= "{$field['title']}: <input name=\"{$field['name']}\" value=\"{$values[$field['name']]}\"/><br/>\n";
        }
    }
    $out .= "Image URI: <input name=\"shopcart_image\" value=\"$image\" $disabled />";
    $out = apply_filters('shopcart_item_meta_form', $out);
    echo $out;
}



//saves the information filled in the meta box on the post edit page
function shopcart_save_info($post_ID)
{
    global $shopcart_item_meta_fields;
    if ($_POST['shopcart_enabled'] == 'true') {
        if (!add_post_meta($post_ID, 'shopcart_enabled', 'true', true)) {
            update_post_meta($post_ID, 'shopcart_enabled', 'true');
        }

        if (trim($_POST['shopcart_price']) != '') {
            add_post_meta($post_ID, 'shopcart_price', number_format((float)$_POST['shopcart_price'], 2), true)
            or  update_post_meta($post_ID, 'shopcart_price', number_format((float)$_POST['shopcart_price'], 2));
        }

        add_post_meta($post_ID, 'shopcart_weight', (float)$_POST['shopcart_weight'], true)
        or  update_post_meta($post_ID, 'shopcart_weight', (float)$_POST['shopcart_weight']);

        add_post_meta($post_ID, 'shopcart_upc', $_POST['shopcart_upc'], true)
        or  update_post_meta($post_ID, 'shopcart_upc', $_POST['shopcart_upc']);

        add_post_meta($post_ID, 'shopcart_image', $_POST['shopcart_image'], true)
        or update_post_meta($post_ID, 'shopcart_image', $_POST['shopcart_image']);
        
        add_post_meta($post_ID, 'shopcart_condition', $_POST['shopcart_condition'], true)
        or update_post_meta($post_ID, 'shopcart_condition', $_POST['shopcart_condition']);
        
        add_post_meta($post_ID, 'shopcart_mpn', $_POST['shopcart_mpn'], true)
        or update_post_meta($post_ID, 'shopcart_mpn', $_POST['shopcart_mpn']);

        foreach ($shopcart_item_meta_fields as $field) {
            add_post_meta($post_ID, $field['name'], $_POST[$field['name']], true)
            or update_post_meta($post_ID, $field['name'], $_POST[$field['name']]);
        }

    } else {
        if (!add_post_meta($post_ID, 'shopcart_enabled', 'false', true)) {
            update_post_meta($post_ID, 'shopcart_enabled', 'false');
        }
    }
}
add_action('save_post', 'shopcart_save_info');


//////////////////////////////////////////////////////////////////////////////

//Adds an options page to the admin dashboard
function shopcart_add_options_page()
{
    $mypage = add_options_page('Shipping Cart Options', 'Shopping Cart', 8, __FILE__, 'shopcart_load_options_page');
    add_action("admin_print_scripts-$mypage", 'shopcart_add_options_javascript');
}
//////////////////////////////////////////////////////////////////////////////

function shopcart_show_full_cart($the_content)
{
    if (!is_paged()) {
        return $the_content;
    }
    $total = 0;
    $out = '';
    $out .= "
        <table>
            <tr>
                <th>Qty</th>
                <th>Item</th>
                <th>Price</th>
                <th>Ext</th>
            </tr>";
            
    foreach ($_SESSION['shopcart']['items'] as $item) {
        $post = get_post($item['id'], ARRAY_A);
        $price = (float)get_post_meta($item['id'], 'price', true);
        $price_str = number_format($price, 2);
        $qty = (int)$item['qty'];
        $ext_price = $price*$qty;
        $ext_price_str = number_format($ext_price, 2);
        $total += $ext_price;
        
        $out .= "
            <tr>
                <td>{$qty}</td>
                <td>{$post['post_title']}</td>
                <td>\${$price_str}</td>
                <td>\${$ext_price_str}</td>
            </tr>";
    }
    $shipping = (float)apply_filters('shopcart_shipping_costs', 0);
    $shipping_str = number_format($shipping, 2);
    $total += $shipping;
    $total_str = number_format($total, 2);
    $out .= "
            <tr>
                <td colspan=\"3\" align=\"right\">Shipping</td>
                <td>\${$shipping_str}</td>
            </tr>
            <tr>
                <td colspan=\"3\" align=\"right\">Total</td>
                <td>\${$total_str}</td>
            </tr>
        </table>";
    return $the_content . '<br/>'. $out;
}
add_action('the_content', 'shopcart_show_full_cart');

//////////////////////////////////////////////////////////////////////////////

function shopcart_add_item_form($content)
{
    if (is_feed()) return $content;
    global $post;
    $enabled = true && (get_post_meta($post->ID, 'shopcart_enabled', true) == 'true');
    if ($enabled) {
        $out = '<form method="POST" action="'.SHOPCART_CART_URL.'"/>';
        $out .= '<input type="hidden" name="item" value="'.$post->ID.'"/>';
        $out .= '<input type="hidden" name="qty" value="1"/>';
        $out .= '<input type="submit" value="Add to Cart"/>';
        $out .= '</form>';
        $out = apply_filters('shopcart_add_to_cart_form', $out);
        return $content . $out;
    } else {
        return $content;
    }
}
add_action('the_content', 'shopcart_add_item_form');


// Hook things in, late enough so that add_meta_box() is defined
if (is_admin()) {
    add_action('admin_menu', 'shopcart_add_box');
    add_action('admin_menu', 'shopcart_add_options_page');
    add_action('admin_print_scripts', 'shopcart_add_post_javascript');
}

// Signal other plugins who might need to load.
function shopcart_init_plugin()
{
    do_action('shopcart_plugin_loaded', $subversion_revision);
}
add_action('plugins_loaded', 'shopcart_init_plugin');
?>